#include "UDPZigbusConnection.h"

UDPZigbusConnection::UDPZigbusConnection(int port, QObject* parent) : AbstractZigbusConnection(parent)
{
    socket = NULL;
    this->port = port;
}

UDPZigbusConnection::~UDPZigbusConnection()
{
    close();
}

bool UDPZigbusConnection::open()
{
    qDebug() << "[Zigbus] opening port...";
    socket = new QUdpSocket(this);
    if(!socket->bind(port)) {
        qDebug() << "[Zigbus] ERROR: fail to listen UDP port "<<port;
        if(socket) {
            delete socket;
            socket = NULL;
        }
        return false;
    }
    qDebug() << "[Zigbus] Now listening UDP port "<<port;
    connect(socket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
    return true;
}

bool UDPZigbusConnection::isOpen() const
{
    return socket && socket->isOpen();
}

void UDPZigbusConnection::close()
{
    qDebug() << "[Zigbus] closing port...";
    if(socket) {
        if(socket->isOpen())
            socket->close();
        delete socket;
        socket = NULL;
    }
    qDebug() << "[Zigbus] port closed";
}

void UDPZigbusConnection::sendMessage(ZigbusMessage message)
{
    QByteArray datagram = message.trame().toLocal8Bit();
    qDebug() << "[Zigbus] send message: " << QString(datagram);
    socket->writeDatagram(datagram.data(), datagram.size(), QHostAddress::LocalHost, 7756);
}

void UDPZigbusConnection::readPendingDatagrams()
{
    qDebug() << "[zigbus] read pending data";
    while (socket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(socket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;
        socket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
        QString data = datagram;
        qDebug() << "data read: "<< data;
        processMessage(data);
    }
}
